package com.pan.studentmaster;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.ContentValues;
import android.content.res.Resources.NotFoundException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.util.Log;

// I will be using this class to download xml and populate informations

public class Initializer {

	public Initializer() {
		if(Student.instance() == null) {
			// no student in database, so add data
			initDB();
			Student.instance();
		}
		initBooks();
	}
	
	private void initDB() {
		SQLiteDatabase db = DB.instance().getWritableDatabase();
		ContentValues cv = new ContentValues();
		XmlPullParserFactory factory;
		try {
			factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			XmlPullParser xpp = factory.newPullParser();
			xpp.setInput(Main.instance().getResources().openRawResource(R.raw.information), null);
			int eventType = xpp.getEventType();
			String school = null;
			int grade = 0;
			String classA = null;
			int course = 0;
			while (eventType != XmlPullParser.END_DOCUMENT) {
				switch(eventType) {
				case XmlPullParser.START_TAG :
					if(xpp.getName().equalsIgnoreCase("school"))
						school = xpp.getAttributeValue(null, "name");
					else if(xpp.getName().equalsIgnoreCase("grade"))
						grade = Integer.parseInt(xpp.getAttributeValue(null, "name"));
					else if(xpp.getName().equalsIgnoreCase("class"))
						classA = xpp.getAttributeValue(null, "name");
					else if(xpp.getName().equalsIgnoreCase("student")) {
						int studentNumber = Integer.parseInt(xpp.getAttributeValue(null, "number"));
						String studentName = xpp.getAttributeValue(null, "name");
						cv.clear();
						cv.put(DB.STUDENT._SCHOOL, school);
						cv.put(DB.STUDENT._GRADE, grade);
						cv.put(DB.STUDENT._CLASS, classA);
						cv.put(DB.STUDENT._NUMBER, studentNumber);
						cv.put(DB.STUDENT._NAME, studentName);
						db.insert(DB.STUDENT._T, null, cv);
						Log.i("INIT", "new student " + studentName);
					}
					else if(xpp.getName().equalsIgnoreCase("course")) {
						cv.clear();
						String courseName = xpp.getAttributeValue(null, "name");
						cv.put(DB.COURSE._NAME, courseName);
						course = (int) db.insert(DB.COURSE._T, null, cv);
						Log.i("INIT", "new course " + courseName + "(" + course + ")");
					}
					else if(xpp.getName().equalsIgnoreCase("book")) {
						cv.clear();
						cv.put(DB.BOOK._COURSE, course);
						String type = xpp.getAttributeValue(null, "type");
						int bookType = type.equals("text") ? DB.BOOK_TEXT :
							type.equals("line") ? DB.BOOK_LINE :
							type.equals("sblock") ? DB.BOOK_SBLOCK :
							type.equals("bblock") ? DB.BOOK_BBLOCK :
							DB.BOOK_BLANK;
						cv.put(DB.BOOK._BOOKTYPE, bookType);
						String title = xpp.getAttributeValue(null, "title");
						cv.put(DB.BOOK._TITLE, title);
						String subTitle = xpp.getAttributeValue(null, "subtitle");
						cv.put(DB.BOOK._SUBTITLE, subTitle);
						cv.put(DB.BOOK._PAGES, Integer.parseInt(xpp.getAttributeValue(null, "pages")));
						db.insert(DB.BOOK._T, null, cv);
						Log.i("INIT", "new book " + title + "/" + subTitle);
					}
					break;
				}
				eventType = xpp.next();
			}
		} catch (NotFoundException e) {
			Log.e("XML", "not found");
		} catch (XmlPullParserException e) {
			Log.e("XML", "parser error:" + e.getMessage());
		} catch (IOException e) {
			Log.e("XML", "IOException "+ e.getMessage());
		}
	}
	
	private void initBooks() {
		// create ThumbNail image for book cover
		Cursor cursor = DB.instance().getBooks(-1);
		while(!cursor.isAfterLast()) {
			int id = cursor.getInt(cursor.getColumnIndex(DB.BOOK._ID));
			String fullpath = Main.instance().getFilesDir().getAbsolutePath() + "/book_" + id + ".png";
			File png = new File(fullpath);
			if(png.exists()) {
				Log.i("INIT", "Thumbnail already exist:" + fullpath);
				cursor.moveToNext();
				continue;
			}
			Log.i("INIT", "Creating thumbnail for " + fullpath);
			Bitmap bmp = BookMaster.instance().getBitmap(id, 0);
			if(bmp != null) {
				Log.i("INIT", "Loaded as bmp");
				bmp = ThumbnailUtils.extractThumbnail(bmp, 200, 300);
				// save to book_id.png
				FileOutputStream foThumbnail;
				try {
					foThumbnail = new FileOutputStream(png);
					bmp.compress(Bitmap.CompressFormat.PNG, 85, foThumbnail);
					foThumbnail.flush();
					foThumbnail.close();
				} catch (Exception e) {
					Log.e("INI", "Failed to create thumbnail for book " + id + " because " + e.getMessage());
				}
				bmp.recycle();
				System.gc();
				Log.i("INIT", "Finished");
			}
			cursor.moveToNext();
		}
	}

}
